<?php
/*
+ ---------------------------------------------------------------------- +
| e107Shop - An e-commerce plugin for the e107 content management system |
|                                                                        |
| ByOrder Europe 2007-2008                                               |
| http://e107shop.com                                                    |
| patrick@byorder.nl                                                     |
|                                                                        |
| Released under the terms and conditions of the LGPL                    |
|                                                                        |
| $Revision: 1.0                                                         |
| $Date: 2008/08/20                                                      |
| $Author: Bieleke                                                       |
+ ---------------------------------------------------------------------- +
*/

function e107shop_add_products_to_cart($productID, $quantity, $options, $cart_id, $field1='', 
$field2='', $field3='', $field4='', $field5='', $field6='', $field7='', $field8='', $field9='', $field10='', $field11='', 
$field12='', $field13='', $field14='', $field15='', $field16='', $field17='', $field18='', $field19='', $field20='') {
    global $e107shop_db_name, $tp;
    $cart_time = time() + 3600;
    $expired_cart = time() - 3600;
    $sql=new db;
    
    // make data safe
    $productID = (int)$productID;
    $quantity  = (int)$quantity;
    $options   = $tp->toDB($options);
    $cart_id   = $tp->toDB($cart_id);
    $field1    = $tp->toDB($field1);
    $field2    = $tp->toDB($field2);
    $field3    = $tp->toDB($field3);
    $field4    = $tp->toDB($field4);
    $field5    = $tp->toDB($field5);
    $field6    = $tp->toDB($field6);
    $field7    = $tp->toDB($field7);
    $field8    = $tp->toDB($field8);
    $field9    = $tp->toDB($field9);
    $field10   = $tp->toDB($field10);
    $field11   = $tp->toDB($field11);
    $field12   = $tp->toDB($field12);
    $field13   = $tp->toDB($field13);
    $field14   = $tp->toDB($field14);
    $field15   = $tp->toDB($field15);
    $field16   = $tp->toDB($field16);
    $field17   = $tp->toDB($field17);
    $field18   = $tp->toDB($field18);
    $field19   = $tp->toDB($field19);
    $field20   = $tp->toDB($field20);
    

    if($sql->db_Select($e107shop_db_name['cart'], "*", "cart_ID='".$cart_id."'")){
        // Update the expire time of all other existing items in users Cart
        $sql->db_Update($e107shop_db_name['cart'], "cart_time='".$cart_time."' where cart_ID='".$cart_id."'");
    }
    $sql->db_Delete($e107shop_db_name['cart'], "cart_time <'".$expired_cart."'");
    // Check if product already exists in cart
    if($sql->db_Select($e107shop_db_name['cart'], "*", "`cart_ID`='".$cart_id."' and `productID` = '".$productID."' and `option` = '".$options."'")){
        while ($row = $sql->db_Fetch()) {
            if ($row['productID'] == $productID) {
                $lineID = $row['lineID'];
                $quantity += $row['quantity'];
                // check stocklevel
                $quantnow = e107shop_check_stocklevel($quantity);
                $sql->db_Update($e107shop_db_name['cart'], "quantity='".$quantnow."' where lineID=".$lineID);
                $added = e107shop_display_shopping_cart($cart_id, $productID);
                return $added;
            }
        }
    }
    $quantnow = e107shop_check_stocklevel($quantity);
    if($sql->db_Insert($e107shop_db_name['cart'], "0, '".$cart_id."','". $productID."','". $quantnow."','". 
    $options."', '".$cart_time."', '".e107shop_order_id()."', '".$field1."', '".$field2."', '".
    $field3."', '".$field4."', '".$field5."', '".$field6."', '".$field7."', '".$field8."', '".
    $field9."', '".$field10."', '".$field11."', '".$field12."', '".$field13."', '".
    $field14."', '".$field15."', '".$field16."', '".$field17."', '".$field18."', '".
    $field19."', '".$field20."'")){
        $added = TRUE;
    } else {
        $added = FALSE;
    }
    return $added;    
}

function e107shop_display_shopping_cart($cart_id) {
    global $e107shop_db_name, $cart_id, $shop_settings, $tp;
    $cart_id = $tp->toDB($cart_id);
    
    $cart .=     "<center><table class='fborder' width='100%'>
                <tr>
                <td class='forumheader' style='text-align: left;'>
                    &nbsp;".lan_global_product_name."
                </td>
                <td class='forumheader'>
                    ".lan_global_quantity."
                </td>";
    
    $cart .=     "<td class='forumheader'>
                ".lan_global_price_per_item."
                </td>
                <td class='forumheader'>
                ".lan_global_action."    
                </td>
                </tr>
                <tr><td colspan='4'>&nbsp;</td></tr>";

    $sql=new db;
    $sql2=new db;
    $tblProducts =  new db;
    
    $dbrows = 0;
    
    if($sql->db_Select($e107shop_db_name['cart'], "*", "cart_ID='".$cart_id."' order by cart_time")) {
        $price = 0;
        $postage_price = 0;
        $total_price = 0;
        $quantity = 0;
        $customFields = array();
        while($row = $sql -> db_Fetch()){
            $customFields = array($row['field1'], $row['field2'], $row['field3'], $row['field4'], $row['field5'], 
            $row['field6'], $row['field7'], $row['field8'], $row['field9'], $row['field10'], 
            $row['field11'], $row['field12'], $row['field13'], $row['field14'], $row['field15'], 
            $row['field16'], $row['field17'], $row['field18'], $row['field19'], $row['field20']);
            //
            // Calculate the price per item
            //
            $line_product_price = e107shop_get_product_field($row["productID"], "special_price");
            if (floatval($line_product_price) == 0) 
                $line_product_price = e107shop_get_product_field($row["productID"], "product_price");
            // Now check if there are option related tot he product
            $options = explode("|", $row["option"]);
            if(is_array($options)) {
                foreach ($options as $value) {
                    $line_option_price = e107shop_get_option_field($value, "optval");
                    $line_product_price += $line_option_price;
                }
            }
            $product_price += $line_product_price * $row['quantity'];

            //
            // Calculate the postage price
            //
            $postage_price += e107shop_get_postage_price($row["productID"], $row['quantity']);
                
            //
            // Display each item from the cart
            //
            if ($dbrows > 0) {
                $cart .="<tr><td colspan='4'><hr /></td></tr>";
            }
            
            $cart .="<tr>
                    <td><div>&nbsp;"
                    .e107shop_get_product_field($row["productID"], "product_name")."</div>";
            
            // check if there are product-options before filling the table
            if (is_array($options)) {
                if ($options['0']) $cart .= "<div style='height: 10px;'>
                                            </div><div>&nbsp;<b>".lan_global_options."</b>";
                foreach ($options as $value) {
                    if ($sql2->db_Select($e107shop_db_name['product_options'], "*", "ID='".$value."'")) {
                        while ($row2=$sql2->db_Fetch()) {
                            $cart .= "<br />&nbsp;".$row2["option_group"].": ".$row2['optname'];
                        }
                    }
                }
                if ($options['0']) $cart .= "</div>";
            }
            
            // now check if the product is customized by the customer
            $firstRecord = 0;
            if ($customFields[0] != '') {
                // retrieve the names of the custom product fields
                $tblProducts->db_Select($e107shop_db_name['products'], "*", "ID='".$row['productID']."'");
                $tblProductsRow = $tblProducts->db_Fetch();
                $customProductFields = array($tblProductsRow['fname_1'], $tblProductsRow['fname_2'], $tblProductsRow['fname_3'], $tblProductsRow['fname_4'], $tblProductsRow['fname_5'], 
                $tblProductsRow['fname_6'], $tblProductsRow['fname_7'], $tblProductsRow['fname_8'], $tblProductsRow['fname_9'], $tblProductsRow['fname_10'], 
                $tblProductsRow['fname_11'], $tblProductsRow['fname_12'], $tblProductsRow['fname_13'], $tblProductsRow['fname_14'], $tblProductsRow['fname_15'], 
                $tblProductsRow['fname_16'], $tblProductsRow['fname_17'], $tblProductsRow['fname_18'], $tblProductsRow['fname_19'], $tblProductsRow['fname_20']);
                $cart .= "<div style='height: 10px;'>
                </div>
                <div>&nbsp;<b>".lan_custom_fields."</b>";
                foreach ($customFields as $value) {
                    if ($value != '') $cart .= "<br />&nbsp;".$customProductFields[$firstRecord].": ".$value;
                    $firstRecord += 1; 
                }
                $cart .= "</div>";
            }

            $cart .= "</td>
                    <td>
                        <center>
                            <form action='cart.php?action=update' method='post'>
                                <input type='hidden' name='lineid' value='".$row["lineID"]."'>
                                <input type='hidden' name='product' value='".$row["productID"]."'>
                                <center>
                                    <input type='text' name='quantity' value='".$row["quantity"]."' size='4' class='tbox' />
                                    <div style='height: 10px;'>
                                        &nbsp;
                                    </div>
                                    <input type='submit' value='".lan_global_update."' />
                                </center>
                            </form>
                        </center>
                    </td>
                    <td>
                        <center>".$shop_settings["currency_symbol"].e107shop_get_numformat($line_product_price)."</center>
                    </td>
                    <td>
                        <form action='cart.php?action=delete' method='post'>
                            <input type='hidden' name='lineid' value='".$row["lineID"]."' />
                            <center>
                                <input type='submit' value='".lan_global_delete."' />
                            </center>
                        </form>
                    </td>
                </tr>";
            $dbrows++;
        }
        
        // calculate and add the tax
        if ($shop_settings['tax_inc'] == 1) $product_price = roundfix(e107shop_calculate_excl($product_price, $shop_settings['tax_rate']), 2);        
        $postage_price = roundfix($postage_price, 2);
        $subtotal = roundfix($product_price + $postage_price, 2);
        $tax = roundfix(e107shop_calculate_tax($subtotal, $shop_settings['tax_rate']), 2);
        $total = $subtotal + $tax;
        $endtrue = FALSE;
        
        $cart .= "<tr><td colspan='4'>&nbsp;</td></tr>
                <tr><td class='forumheader' colspan='4'><b>".lan_price_information."</b></td></tr>";
        
        // Add price exclusive vat
        $cart .=   "<tr><td><div style='height: 5px;'>&nbsp;</div></td></tr>
                    <tr><td colspan='2' style='font-size: 10pt; text-align: right;'>
                        <b>".lan_price_exclusive."</b>
                     </td>
                     <td style='font-size: 10pt; text-align: right;'>
                        <b>".$shop_settings["currency_symbol"].e107shop_get_numformat($product_price)."</b>
                     </td>
                     <td>
                        &nbsp;
                     </td>
                </tr>";
        
        if($shop_settings["postage_method"] == "2" || $shop_settings["postage_method"] == "1"){
            $cart .="<tr>
                <td colspan='2' style='font-size: 10pt; text-align: right;'>
                    <b>".lan_global_postage."</b></td>";
            $endtrue = TRUE;
        }
        if($shop_settings["postage_method"] == "2"){
            $cart .="<td style='font-size: 10pt; text-align: right;'>
            <b>".$shop_settings["currency_symbol"].e107shop_get_numformat($postage_price)."</b>";
        } else if($shop_settings["postage_method"] == "1"){
            $cart .="<td style='font-size: 10pt; text-align: right; color: #618B31;'>
            <b>".lan_global_postage_included."</b>";
        }
        
        // display subtotal price only when postage is 1 or 2
        if ($endtrue == TRUE) $cart .="</td><td>&nbsp;</td></tr>
                <tr>
                 <td colspan='2' style='font-size: 10pt; text-align: right;'>
                     <b>".lan_global_subtotal."</b>
                 </td>
                 <td style='font-size: 10pt; text-align: right;'>
                     <b>".$shop_settings["currency_symbol"].e107shop_get_numformat($subtotal)."</b>
                 </td>
                 <td>
                     &nbsp;
                 </td>
             </tr>";
                        
        //
        // Display the tax information in the cart
        //
        $cart .="<tr>
                    <td colspan='2' style='font-size: 10pt; text-align: right;'>
                        <b>".lan_global_tax."</b>
                    </td>
                    <td style='font-size: 10pt; text-align: right;'>
                        <b>".$shop_settings["currency_symbol"].e107shop_get_numformat($tax)."</b>
                    </td>
                    <td>
                        &nbsp;
                    </td>
                </tr>";
                
        if($shop_settings["postage_method"] == "3" || $shop_settings["postage_method"] == "4"){
            $cart .="<tr><td colspan='4'>&nbsp;</td></tr>
            <tr>
                <td colspan='4' style='font-size: 10pt; text-align: center;'><b>
                    ".lan_postage_calculated_next."</b>
                </td>
            </tr>";
        }

        //
        // Display the totals
        //
        $cart .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>
                <tr>
                <td class='forumheader' style='text-align: right; font-size: 10pt;' colspan='2'><b>"
                .lan_global_total_price."</b></td>
                <td class='forumheader' style='text-align: right; font-size: 10pt;'>
                    <b>".$shop_settings["currency_symbol"].
                    e107shop_get_numformat($total)."</b>
                </td>
                <td class='forumheader'>
                    &nbsp;
                </td>
                </tr>
                <tr><td colspan='4'>&nbsp;</td></tr>";
        $cart .=    "<tr>
                    <td colspan='4'>
                    <div style='float: left; width: 33%; text-align: center;'>
                    <form action='index.php' method='post'>
                        <input type='hidden' name='backup' value=''>
                        <div>
                        <input type='submit' value='".lan_global_continue_shopping."' style='font-size: 10pt;'>
                        </div>
                    </form>
                    </div>
                    <div style='float: left; width: 33%; text-align: center;'>
                    <form action='cart.php?action=empty' method='post'>
                        <input type='submit' value='".lan_empty_cart."' style='font-size: 10pt;'>
                    </form>
                    </div>
                    <div style='float: left; width: 33%; text-align: center;'>
                    <form action='checkout.php' method='post'>
                        <input type='submit' value='".lan_global_checkout."' style='font-size: 10pt;' />
                        <input type='hidden' name='postage' value='".$postage_price."'>
                    </form>
                    </div>
                    </td>
                    </tr>
                    <tr><td colspan='4'>&nbsp;</td></tr>";
    
        $cart.="</table>";
    } else {
        $cart = "<table class='fborder' width='100%'>
            <tr>
            <td class='forumheader' style='text-align: left;'> 
                ".lan_global_nav_to."<a href='index.php'>"
                .lan_global_mainpage."</a> --> ".lan_global_shopping_cart."
            </td>
            </tr>
            </table>
            <div style='width: 100%; padding: 5px; font-size: 10pt;'>"
            .lan_global_cart_empty_complete."</div>";
    }
    $tblProducts->db_Close();
    return $cart;
}

function e107shop_update_cart($lineID, $quantity, $productID){
    global $e107shop_db_name, $tp;
    $lineID   = (int)$lineID;
    $quantity = (int)$quantity;
    $productID = $tp->toDB($productID);
    $cart_time = time() + ((3600 * 2) * 1);
    $sql=new db;
    
    if($quantity=="0"){
        $sql->db_Delete($e107shop_db_name['cart'], "lineID=".$lineID);
    } else {
        $quantnow = e107shop_check_stocklevel($quantity);
        if($sql->db_Update($e107shop_db_name['cart'], "quantity='".$quantnow."' where lineID=".$lineID)){
        } else {
            $updated = "<center>".lan_global_error;
        }
    }
    return $updated;    
}

function e107shop_empty_cart($cart_id){
    global $e107shop_db_name, $tp;
    $cart_id = $tp->toDB($cart_id);
    $sql=new db;
    $sql->db_Delete($e107shop_db_name['cart'], "cart_ID='".$cart_id."'");
}

function e107shop_order_id(){
    global $e107shop_db_name, $cart_id, $sql, $shop_settings, $tp;
    
    $cart_id = $tp->toDB($cart_id);
    if(!$sql->db_Select($e107shop_db_name['cart'], "*", "cart_id='".$cart_id."'"))
    {
        $order_id = $shop_settings["orderID"] + 1;
        $sql=new db;
        $sql->db_Update($e107shop_db_name['settings'], "orderID='".$order_id."'");
        
    }
    else
    {
        while($row = $sql->db_Fetch())
        {
            $order_id = $row["order_number"];
        }
    }
    // format the order as a numer padded with zero's
    $order_id = sprintf('%06d', $order_id);
    return $order_id;

}

function e107shop_check_stocklevel($quantity) {
    global $shop_settings, $e107shop_db_name, $cart_id, $productID;
    $sql_cl = new db;
    $sql_sl = new db;
    $counter1 = $sql_cl->db_Select($e107shop_db_name['cart'], "quantity", "cart_ID='".$cart_id."'");
    $result1 = 0;
    $result2 = 0;
    $wanted = 0;
    if ($counter1 > 0) {
        $row = $sql_cl->db_Fetch(MYSQLI_ASSOC);
        $cartlevel = $row['quantity'];
    }
    $wanted = $quantity; 
    if ($shop_settings['sell_into_minus_stock'] == 1) return $wanted;
    $counter2 = $sql_sl->db_Select($e107shop_db_name['products'], "stock_on_hand", "ID='".$productID."'");
    if ($counter2 > 0) {
        $row2 = $sql_sl->db_Fetch(MYSQLI_ASSOC);
        $alowed = $row2['stock_on_hand'];
        if ($wanted > $alowed) {
            $result = $alowed;
            echo "<script language='JavaScript'>window.alert('".lan_alert_part1." ".$alowed." ".lan_alert_part2."')</script>";
        }
        else $result = $quantity;
    }
    $sql_cl->db_Close();
    $sql_sl->db_Close();
    return $result;
}
